package com.example.demo.controller;

import com.example.demo.RoomDeal.Room;
import com.example.demo.RoomDeal.RoomManager;
import com.example.demo.constant.Constants;
import com.example.demo.game.GameReadyResponse;
import com.example.demo.model.OnlineUserManager;
import com.example.demo.model.domian.User;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Component
@Slf4j
public class GameController extends TextWebSocketHandler {
    GameReadyResponse response=new GameReadyResponse();
    ObjectMapper mapper=new ObjectMapper();
    @Autowired
    RoomManager roomManager;
    @Autowired
    OnlineUserManager onlineUserManager;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        //1.获取当前游戏房间内用户信息,为了防止用户直接访问我们的游戏房间界面
        User user= (User) session.getAttributes().get(Constants.USER_SESSION_KEY);
        if (user==null){
            response.setOk(false);
            response.setReason("当前用户未登录");
            session.sendMessage(new TextMessage(mapper.writeValueAsString(response)));
            return;
        }
        //2.判断当前用户是否已经进入房间
        Room room=roomManager.getRoomByUserId(user.getUserId());
        if (room==null){
            response.setOk(false);
            response.setReason("当前用户未进入房间");
            session.sendMessage(new TextMessage(mapper.writeValueAsString(response)));
            return;
        }
        //3.判断是否是多开
        if (onlineUserManager.getFromGameHall(user.getUserId())!=null
            ||onlineUserManager.getFromRoom(user.getUserId())!=null){
            response.setOk(false);
            response.setReason("当前用户已经登录");
            session.sendMessage(new TextMessage(mapper.writeValueAsString(response)));
            session.close();
            return;
        }
        //4.排除上述错误后,将玩家在游戏房间内设置为登录
        onlineUserManager.enterGameRoom(user.getUserId(), session);
        log.info("当前用户 user {}",user.getUsername());
        //5.把两个游戏玩家加入到我们的房间中
        if (room.getUser1()==null){
            room.setUser1(user);
            room.setWhiteUser(user.getUserId());
            return;
        }
        if (room.getUser2()==null){
            room.setUser2(user);
            //服务器返回响应给双方,告知双方准备就绪
            //因为当第二个人进入房间之后人就齐了


            //user1是当前玩家,user2是目标玩家
            noticeGameReday(room,room.getUser1(),room.getUser2());

            //user2是当前玩家,user1是目标玩家
            noticeGameReday(room,room.getUser2(),room.getUser1());
        }

    }

    private void noticeGameReday(Room room, User thisUser, User thatUser) throws IOException {
        GameReadyResponse resp=new GameReadyResponse();
        resp.setMessage("gameReady");
        resp.setOk(true);
        resp.setReason("");
        resp.setRoomId(room.getRoomId());
        resp.setThisUserId(thisUser.getUserId());
        resp.setThatUserId(thatUser.getUserId());
        resp.setWhiteUser(room.getWhiteUser());
        // 把当前的响应数据传回给玩家.
        WebSocketSession webSocketSession = onlineUserManager.getFromRoom(thisUser.getUserId());
        webSocketSession.sendMessage(new TextMessage(mapper.writeValueAsString(resp)));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        User user= (User) session.getAttributes().get(Constants.USER_SESSION_KEY);
        if (user==null){
            return;
        }
        WebSocketSession exitSession = onlineUserManager.getFromRoom(user.getUserId());
        if (session==exitSession){
            onlineUserManager.exitGameHall(user.getUserId());
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        User user= (User) session.getAttributes().get(Constants.USER_SESSION_KEY);
        if (user==null){
            return;
        }
        WebSocketSession exitSession = onlineUserManager.getFromRoom(user.getUserId());
        if (session==exitSession){
            onlineUserManager.exitGameHall(user.getUserId());
        }
    }
}
